package com.example.compose


import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.StrictMode
import android.provider.MediaStore
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.IconButton
import androidx.compose.material.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.Lifecycle
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.example.compose.ui.camera.CameraPreview
import com.example.compose.ui.dialog.FeatureThatRequiresPermission
import com.example.compose.ui.theme.StarLightsTheme
import com.example.compose.ui.wifi.WIFIManager
import com.example.compose.utils.FileUtils
import com.example.compose.utils.cx
import com.example.compose.utils.dip
import com.google.accompanist.permissions.ExperimentalPermissionsApi

val ActiveLifecycle = compositionLocalOf<Lifecycle> { error("No active lifecycle found!") }

class StarActivity : ComponentActivity() {

    private lateinit var cropImageUri:Uri
    private val getBackValue2 = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
        if(it.resultCode == Activity.RESULT_OK){

        }
    }
    private val getBackValue1 = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
        if(it.resultCode == Activity.RESULT_OK){
            cropImage(this, cropImageUri)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        UpdateApp().versionUpdate(this)
        val wifiManager = WIFIManager(context = baseContext)
        var scanResults = wifiManager.scanResults()
        var connectionInfo = wifiManager.connectionInfo()
        val intent = Intent()
        intent.action = MediaStore.ACTION_IMAGE_CAPTURE   //拍照界面的隐式意图
        cropImageUri = Uri.fromFile(FileUtils.makeFile("测试测试.png", 1))
        intent.putExtra(MediaStore.EXTRA_OUTPUT,cropImageUri)
        //取消严格模式  FileProvider
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            val builder: StrictMode.VmPolicy.Builder = StrictMode.VmPolicy.Builder()
            StrictMode.setVmPolicy(builder.build())
        }

//        getBackValue1.launch(intent)

        setContent {
            StarLightsTheme {
                Surface(
                    modifier = Modifier.fillMaxSize()
                ) {
                    CompositionLocalProvider(ActiveLifecycle provides lifecycle) {
                        Home {
                            startActivity(Intent(this@StarActivity,GreetingCardActivity::class.java))
                        }
                    }
                }
            }
        }
    }

    private fun cropImage(activity: Activity, srcUri: Uri) {
        cropImageUri = srcUri
        val intent = Intent("com.android.camera.action.CROP")
        intent.setDataAndType(srcUri, "image/*")
        intent.putExtra("crop", "true")

        // aspectX aspectY 是裁剪框宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
//        // outputX outputY 是裁剪后生成图片的宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);

        // return-data为true时,会直接返回bitmap数据,但是大图裁剪时会出现问题,推荐下面为false时的方式
        // return-data为false时,不会返回bitmap,但需要指定一个MediaStore.EXTRA_OUTPUT保存图片uri
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropImageUri)
        intent.putExtra("return-data", false)
        getBackValue2.launch(intent)
    }
}


@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun Home(onClick:()->Unit) {
    val starList = listOf(
        StarScreen.FirstPage,
        StarScreen.SecondPage,
        StarScreen.ThirdPage,
        StarScreen.FourthPage
    )
    val bottom = remember { mutableStateOf(0f) }
    val top = remember { mutableStateOf(0f) }
    val currentScreen = remember { mutableStateOf(StarScreen.FirstPage as StarScreen) }
    val navController: NavHostController =  rememberNavController()
    val mutableTransitionState = MutableTransitionState(true)
    var navBackStackEntry: NavBackStackEntry? = null
    ViewCompat.setOnApplyWindowInsetsListener(LocalView.current) { v, insets ->
        bottom.value = insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom.dip
//        insets.getInsets(WindowInsetsCompat.Type.ime()).bottom.dip
        top.value = insets.getInsets(WindowInsetsCompat.Type.statusBars()).top.dip
//        val imeHeight = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom
//        v.setPadding(
//            0,
//            0,
//            0,
//            imeHeight + insets.getInsets(WindowInsetsCompat.Type.navigationBars()).bottom
//        )
        insets
    }
    Image(
        painter = painterResource(id = R.mipmap.bg),
        contentScale = ContentScale.Crop,
        modifier = Modifier.fillMaxSize(),
        alignment = Alignment.Center,
        contentDescription = null
    )
    Box(
        contentAlignment = Alignment.BottomCenter,
        modifier = Modifier.padding(0.dp, 0.dp, 0.dp, bottom.value.dp)
    ) {
        NavHost(navController, StarScreen.PermissionDialogPage.route,
            Modifier
                .fillMaxSize()
                .padding(0.dp, 0.dp, 0.dp, 48.cx.dp)) {
            composable(StarScreen.FirstPage.route) { backStackEntry ->
                run {
                    navBackStackEntry = backStackEntry
                    CameraPreview()
                }
            }
            composable(StarScreen.SecondPage.route) { backStackEntry ->
                run {
                    navBackStackEntry = backStackEntry
                    AppView(Modifier.padding(top.value.dp, 0.dp, 0.dp, 0.dp))
                }
            }
            composable(StarScreen.ThirdPage.route) { backStackEntry ->
                run {
                    navBackStackEntry = backStackEntry

                }
            }
            composable(StarScreen.FourthPage.route) { backStackEntry ->
                run {
                    navBackStackEntry = backStackEntry
                    DefaultPreview11 { onClick()}
                }
            }
            composable(StarScreen.PermissionDialogPage.route) { backStackEntry ->
                run {
                    FeatureThatRequiresPermission(
                        permissions = mutableListOf(android.Manifest.permission.CAMERA,android.Manifest.permission.READ_EXTERNAL_STORAGE
                            ,android.Manifest.permission.WRITE_EXTERNAL_STORAGE),
                        onSuccess = {
                            if (backStackEntry.lifecycle.currentState == Lifecycle.State.RESUMED) {
                                navController.navigate(StarScreen.FirstPage.route)
                            }
                        },
                        onFail = {
                            if (backStackEntry.lifecycle.currentState == Lifecycle.State.RESUMED) {
                                navController.popBackStack()
                            }
                        },
                        lifecycle = ActiveLifecycle.current
                    )
                }
            }
        }
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .clip(RoundedCornerShape(topStart = 27.dp, topEnd = 27.dp))
                .background(Color.Black)
                .padding(vertical = 10.dp)
            ,
            horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically
        ) {
            repeat(starList.size) {
                ItemButton(
                    screen = starList[it],
                    selected = currentScreen.value,
                    onSelected = { screen ->
                        if (navBackStackEntry?.lifecycle?.currentState == Lifecycle.State.RESUMED || navBackStackEntry == null) {
                            navController.navigate(screen.route)
                            mutableTransitionState.targetState = !mutableTransitionState.targetState
                            currentScreen.value = screen
                        }
                    }
                )
            }
        }
    }
}

@Composable
fun ItemButton(
    screen: StarScreen,
    selected: StarScreen,
    onSelected: (StarScreen) -> Unit
) {
    IconButton(
        modifier = Modifier.width(90.cx.dp),
        onClick = {
            onSelected(screen)
        }
    ) {
        Image(
            painter = painterResource(id = if (screen==selected) screen.select!! else screen.default!! ),
            modifier = Modifier.size(48.cx.dp),
            contentDescription = null
        )
    }
}
